# -*- encoding: utf-8 -*-

"""
封装request基础方法
"""

import urllib3
import requests
from retry import retry
from Common.log import MyLog
import json


class Request:

    def __init__(self):
        self.log = MyLog

    @retry((Exception, requests.ConnectionError), tries=3, delay=1, backoff=2, max_delay=4)
    def base_request(self, method, url, headers: dict, body=None, files=None, params=None, time_out=60):
        """
        重新封装request请求方法
        :param params:
        :param method: 请求方法（如get），必填
        :param url: 请求url，必填
        :param headers: 请求头
        :param body: 请求体，post方法请求时需带上，非必填
        :param files: from上传文件方法，请求体，post方法请求时需带上，非必填
        :param time_out: 请求超时时间，默认60秒
        :return: 借口响应数据
        """

        # 将请求体由dict格式转换成json格式
        # body = json.dumps(body)

        self.log.info('请求的url: %s' % str(url))
        self.log.info('请求的method: %s' % str(method))
        self.log.info('请求的body: %s' % str(body))
        self.log.info('请求的header: %s' % str(headers))

        # 关闭警告
        urllib3.disable_warnings()

        try:
            response = requests.request(method, url, headers=headers, data=body, files=files, params=params, verify=False,
                                        timeout=time_out)
        except requests.RequestException as e:
            self.log.info('%s%s' % ('RequestException url: ', url))
            self.log.info(e)
            raise RuntimeError(e)
        except Exception as e:
            self.log.info('%s%s' % ('Exception url: ', url))
            self.log.info(e)
            raise RuntimeError(e)

        # time_consuming为响应时间，单位为毫秒
        # time_consuming = response.elapsed.microseconds / 1000
        # time_total为响应时间，单位为秒
        time_total = response.elapsed.total_seconds()

        self.log.info('响应码：%s' % response.status_code)
        self.log.info('响应体：%s' % response.text)
        self.log.info('请求总耗时：%s' % time_total)

        return response
